import { nativeTheme, Tray, app, Menu, MenuItem, ipcMain } from 'electron'
import path from 'path'
import { MainWindow } from 'app/window'
import { APP_NAME } from 'app/config'
import { IpcEvent } from 'app/type'

export class ElectronTray {
    private static tray: Tray
    private static light: string
    private static dark: string
    private static menu: any[] = [
        { label: '打开应用', click: MainWindow.restore },
        { label: '退出', click: app.quit },
    ]

    static setImage(light = 'status_light.png', dark = 'status_dark.png') {
        ElectronTray.light = path.join(__dirname, '..', '..', 'resources', 'tray', light)
        ElectronTray.dark = path.join(__dirname, '..', '..', 'resources', 'tray', dark)
        ElectronTray.tray?.setImage(
            nativeTheme.shouldUseDarkColors ? ElectronTray.dark : ElectronTray.light,
        )
    }

    static setTray() {
        ElectronTray.tray = new Tray(
            nativeTheme.shouldUseDarkColors ? ElectronTray.dark : ElectronTray.light,
        )
    }

    static setTitle(title: string) {
        ElectronTray.tray?.setTitle(title)
    }

    static setToolTip(tooltip: string) {
        ElectronTray.tray?.setToolTip(tooltip)
    }

    static setContextMenu(trayMenuList: any[] = []) {
        const menu = Menu.buildFromTemplate([...trayMenuList, ...ElectronTray.menu])
        ElectronTray.tray?.setContextMenu(menu)
    }

    static init() {
        ElectronTray.setImage()
        ElectronTray.setTray()
        ElectronTray.setToolTip(APP_NAME)
        ElectronTray.setContextMenu()
        ElectronTray.tray?.on('double-click', MainWindow.restore)
        nativeTheme.on('updated', () => {
            ElectronTray.tray?.setImage(
                nativeTheme.shouldUseDarkColors ? ElectronTray.dark : ElectronTray.light,
            )
        })
        ipcMain.handle(IpcEvent.TRAY_SET_IMAGE, (e, option: string) => {
            const op = JSON.parse(option)
            ElectronTray.setImage(op.light, op.dark)
        })
        ipcMain.handle(IpcEvent.TRAY_SET_TITLE, (e, title: string) => {
            ElectronTray.setTitle(title)
        })
        ipcMain.handle(IpcEvent.TRAY_SET_TOOLTIP, (e, tooltip: string) => {
            ElectronTray.setToolTip(tooltip)
        })
        ipcMain.handle(IpcEvent.TRAY_SET_CONTEXT_MENU, (e, trayMenuList: string) => {
            ElectronTray.setContextMenu(JSON.parse(trayMenuList))
        })
    }
}
